/******************************************************************************
**
** File name: 	utimer.c
**
** Description:	RTOS Unit Test System Library. This module implements timer-
**				counter configuration that is required to simulate periodic HW 
**				interrupts.
**
** Note:		Targets supported that are currently supported by this module:
**
**				- ATXmega32D4 (AVRSIM)		TCC0, TCD0, TCE0 
**
**				TBD: Add static configuration of the target HW. 
**				TBD: Add actual HW support. 
**
*******************************************************************************
** Change history:
**	
** 11/20/2011 - AK - File created. 
** 19/03/2012 - AK - Adopted for AVR Studio V5.1. 
** 
******************************************************************************/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "utimer.h"

/******************************************************************************
**
** FUNCTION:	void utst_init_timer( UTST_TIMER_t * tmr )
**
** DESCRIPTION:	Configures specified ATXmega timer-counter module to generate 
**				periodic interrupt of desired level. 
**				
** PASSED:      The function accepts the pointer to the timer-counter
**				configuration structure ( defined in utimer.h )
**				UTST_TIMER_t	usr_tmr	=
**				{
**					TC0_t *				addr;		base of the timer I/O 
**													space, f.e. &TCC0.
**					unsigned short 		period;	    0...65535 ticks ( actual 
**													interval depends on input 
**													frequency )
**					UTST_TLV_t	 		level;		interrupt level, i.e. 
**													LEVEL_LOW, LEVEL_MED or
**													LEVEL_HIGH
**					UTST_TST_t 			state;	    initial timer state, i.e. 
**													STATE_STOP, STATE_RUN
**				};
** RETURNS:		void
** USES:		-
** STACK:		-
** CALLS:		-
** ASSUMES:		-
** NOTES:		This function
**				is designed for ATXmega32D4 target MCU and AVRSIM simulator
**				environment, however should properly work on real 32D4 HW.
**
******************************************************************************/

void utst_init_timer(UTST_TIMER_t * tmr) 
{
	tmr->addr->CTRLA = ( tmr->addr->CTRLA & ~TC0_CLKSEL_gm ) | TC_CLKSEL_OFF_gc;
	tmr->addr->CNT = 0;
	tmr->addr->PER = tmr->period;
	tmr->addr->INTCTRLA = ( tmr->addr->INTCTRLA & ~TC0_OVFINTLVL_gm ) | TC_OVFINTLVL_LO_gc ;
	if ( tmr->state == STATE_RUN )
	{
		tmr->addr->CTRLA = ( tmr->addr->CTRLA & ~TC0_CLKSEL_gm ) | TC_CLKSEL_DIV1_gc;
	}
}


